#!/usr/bin/python3
'''
Created on Mar 8, 2016

@author: grind
'''

import urllib.request
import urllib.response
import urllib.error
import time

def opensina(code):
    request = urllib.request.urlopen("http://hq.sinajs.cn/list=" + code)
    html = request.read()
    details = html.decode("gbk")
    array = details.split("=")
    #print(array[1])
    item = array[1].split(",")
    #print(type(item))
    volume = float(item[9])

    
    # time, cur, high, low, vol
    return [item[-2], item[3], item[4], item[5], volume/10000]
    #return '[%s] %s(%.2f,%.2f), [%s,%s] vol:%d' % (item[-2], item[3], offset2, offset1, item[4], item[5], volume/10000)

def formatData(items, lastvol):
    offset1 = float(items[1]) - float(items[2])
    offset2 = float(items[1]) - float(items[3])
    return '[%s] %s(%.2f,%.2f), [%s,%s] vol:%d(%.1f)' % (items[0], items[1], offset2, offset1, items[2], items[3],
                                                      items[4], float(items[4]) - float(lastvol))
    
if __name__ == '__main__':
    lastvol1 = 0
    lastvol2 = 0
    while True:
        items  = opensina("sh000001")
        result = formatData(items, lastvol1)
        lastvol1 = items[4];
        print(result, end=' || ')
        #result2 = opensina("sz399001")
        items = opensina("sz399006")
        result2 = formatData(items, lastvol2)
        lastvol2 = items[4];
        print(result2)
        #break
        time.sleep(30) # sleep 2 s
        